package com.saicmotor.livedata;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.saicmotor.livedata.bean.AccountBean;
import com.saicmotor.livedata.viewModel.AccountModel;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    // ViewModel
    private AccountModel model;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView = findViewById(R.id.tv_viewModel);
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment,new FragmentTest()).commit();
        model = ViewModelProviders.of(this).get(AccountModel.class);
        findViewById(R.id.bt_change).setOnClickListener(this);
        // 观察
        model.getAccount().observe(this, new Observer<AccountBean>() {
            @Override
            public void onChanged(AccountBean accountBean) {
                textView.setText(new StringBuilder().append(accountBean.getName()).append("-")
                        .append(accountBean.getPhone()).append("-")
                        .append(accountBean.getBlog()).toString());
            }
        });
    }

    @Override
    public void onClick(View v) {
        // 设置一条数据
        model.setAccount("zzz", "111", "www");
        // post一条数据
        model.getAccount().postValue(new AccountBean("zzz", "111", "www"));
        // TODO:set和post的区别？
        // set:主线程调用
        // post:任意线程调用
    }
}